package com.swpu.cbg.cnshop.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.squareup.okhttp.Response;
import com.swpu.cbg.cnshop.Constans;
import com.swpu.cbg.cnshop.R;
import com.swpu.cbg.cnshop.bean.User;
import com.swpu.cbg.cnshop.http.OkHttpHelper;
import com.swpu.cbg.cnshop.http.SpotsCallback;
import com.swpu.cbg.cnshop.msg.LoginResMsg;
import com.swpu.cbg.cnshop.utils.CountTimerView;
import com.swpu.cbg.cnshop.utils.DESUtil;
import com.swpu.cbg.cnshop.utils.ManifestUtil;
import com.swpu.cbg.cnshop.utils.ToastUtil;
import com.swpu.cbg.cnshop.widget.ClearEditText;
import com.swpu.cbg.cnshop.widget.cnToolbar;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;
import dmax.dialog.SpotsDialog;

/**
 * Created by chenboge on 16/2/18.
 */
public class RegisterScendActivity extends BaseActivity implements View.OnClickListener {

    private OkHttpHelper mHelper = OkHttpHelper.getInstance();
    private String phone;
    private String password;
    private String countryCode;

    private CountTimerView countTimerView;

    private SpotsDialog dialog;

    //private OkHttpHelper okHttpHelper = OkHttpHelper.getInstance();

    private SMSEvenHanlder evenHanlder;

    @ViewInject(R.id.toolbar)
    private cnToolbar mToolbar;


    @ViewInject(R.id.txtTip)
    private TextView mTxtTip;

    @ViewInject(R.id.btn_reSend)
    private Button mBtnResend;

    @ViewInject(R.id.edittxt_code)
    private ClearEditText mEtCode;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg_second);

        ViewUtils.inject(this);
        initToolbar();

        phone = getIntent().getStringExtra(Constans.BaseUserInf.PHONE);
        password = getIntent().getStringExtra(Constans.BaseUserInf.PASSWORD);
        countryCode = getIntent().getStringExtra(Constans.BaseUserInf.COUNTRYCODE);

        String formatedPhone = "+" + countryCode + " " + splitPhoneNum(phone);


        String text = getString(R.string.smssdk_send_mobile_detail) + formatedPhone;
        mTxtTip.setText(Html.fromHtml(text));


        CountTimerView timerView = new CountTimerView(mBtnResend);
        timerView.start();

        SMSSDK.initSDK(RegisterScendActivity.this, ManifestUtil.getMetaDataValue(this, "mob_sms_appKey"),
                ManifestUtil.getMetaDataValue(this, "mob_sms_appSecrect"));

                evenHanlder = new SMSEvenHanlder();
        SMSSDK.registerEventHandler(evenHanlder);

        dialog = new SpotsDialog(this);
        dialog = new SpotsDialog(this, "正在校验验证码");
    }


    /**
     * 分割电话号码
     */
    private String splitPhoneNum(String phone) {
        StringBuilder builder = new StringBuilder(phone);
        builder.reverse();
        for (int i = 4, len = builder.length(); i < len; i += 5) {
            builder.insert(i, ' ');
        }
        builder.reverse();
        return builder.toString();
    }


    private void initToolbar() {
        mToolbar.hideContent();
        mToolbar.showTitle();
        mToolbar.hideRightButton();
        mToolbar.setEditButtonText("完成");
        mToolbar.showEditButton();
        mToolbar.getmEditButton().setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        submitCode();
    }

    private void submitCode() {

        String vCode = mEtCode.getText().toString().trim();

        if (TextUtils.isEmpty(vCode)) {
            ToastUtil.showToast(this, R.string.smssdk_write_identify_code);
            return;
        }
        SMSSDK.submitVerificationCode(countryCode, phone, vCode);
        dialog.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(evenHanlder);
    }

    class SMSEvenHanlder extends EventHandler {


        @Override
        public void afterEvent(final int event, final int result,
                               final Object data) {


            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (dialog != null && dialog.isShowing())
                        dialog.dismiss();

                    if (result == SMSSDK.RESULT_COMPLETE) {
                        if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {

                            //提交验证码成功
                            doReg();
                            dialog.setMessage("正在提交注册信息");
                            dialog.show();
                            ;
                        }
                    } else {

                        // 根据服务器返回的网络错误，给toast提示
                        try {
                            ((Throwable) data).printStackTrace();
                            Throwable throwable = (Throwable) data;
                            JSONObject object = new JSONObject(
                                    throwable.getMessage());
                            String des = object.optString("detail");
                            if (!TextUtils.isEmpty(des)) {
                               ToastUtil.showToast(RegisterScendActivity.this, des);
                                return;
                            }
                        } catch (Exception e) {
                            SMSLog.getInstance().w(e);
                        }

                    }


                }
            });
        }
    }


    @OnClick(R.id.btn_reSend)
    public void reSendCode(View view) {

        SMSSDK.getVerificationCode("+" + countryCode, phone);
        countTimerView = new CountTimerView(mBtnResend, R.string.smssdk_resend_identify_code);
        countTimerView.start();

        dialog.setMessage("正在重新获取验证码");
        dialog.show();
    }


    private void doReg() {

        Map<String, Object> params = new HashMap<>(2);
        params.put("phone", phone);
        params.put("password", DESUtil.encode(Constans.DES_KEY, password));

        mHelper.post(Constans.API.REG, params, new SpotsCallback<LoginResMsg<User>>(this) {

            @Override
            public void onSuccess(Response response, LoginResMsg<User> userLoginResMsg) {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                if (userLoginResMsg.getStatu() == LoginResMsg.STATE_ERROR) {
                    ToastUtil.showToast(RegisterScendActivity.this, "注册失败:" + userLoginResMsg.getMessage());
                    return;
                }
                MyApplication application = MyApplication.getInstanse();
                application.putUser(userLoginResMsg.getData(), userLoginResMsg.getToken());

                startActivity(new Intent(RegisterScendActivity.this, MainActivity.class));
                finish();
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }

            @Override
            public void onTokenError(Response response, int code) {
                //super.onTokenError(response, code);
            }
        });
    }


}
